package com.huayal.mall.product.controller;

import java.net.BindException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.huayal.common.validator.group.AddGroup;
import com.huayal.common.validator.group.UpdateGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.huayal.mall.product.entity.BrandEntity;
import com.huayal.mall.product.service.BrandService;
import com.huayal.common.utils.PageUtils;
import com.huayal.common.utils.R;

import javax.validation.Valid;


/**
 * 品牌
 *
 * @author huayal
 * @email efry@qq.com
 * @date 2024-11-01 20:27:01
 */
@RestController
@RequestMapping("product/brand")
public class BrandController {
    @Autowired
    private BrandService brandService;

    //Test
    @GetMapping("/all")
    public R queryAllBrand() {
        BrandEntity brandEntity = new BrandEntity();
        return R.ok().put("Brands", brandEntity);
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = brandService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{brandId}")
    public R info(@PathVariable("brandId") Long brandId) {
        BrandEntity brand = brandService.getById(brandId);

        return R.ok().put("brand", brand);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@Validated(AddGroup.class) @RequestBody BrandEntity brand) {
        brandService.save(brand);

        return R.ok();
    }
//处理异常例子
//    @RequestMapping("/save")
//    public R save(@Valid @RequestBody BrandEntity brand, BindingResult result) {
//        if (result.hasErrors()){
//            Map<String, String> map = new HashMap<>();
//            List<FieldError> fieldErrors = result.getFieldErrors();
//            for (FieldError fieldError:fieldErrors){
//                String field = fieldError.getField();
//                String defaultMessage = fieldError.getDefaultMessage();
//                map.put(field,defaultMessage);
//            }
//            return R.error(400,"提交的表单数据不合法").put("data",map);
//        }
//        brandService.save(brand);
//
//        return R.ok();
//    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@Validated(UpdateGroup.class) @RequestBody BrandEntity brand) {
//        brandService.updateById(brand);
        brandService.updateDetail(brand);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] brandIds) {
        brandService.removeByIds(Arrays.asList(brandIds));

        return R.ok();
    }

}
